<template>
  <div>
    <el-form ref="form" :rules="rules" :model="form1" label-width="100px" style="width: 500px;" class="demo-ruleForm">
      <el-form-item label="品名" prop="name">
        <el-input v-model="form1.name" placeholder="请输入品名"></el-input>
      </el-form-item>
      <el-form-item label="产品类型" prop="type1">
        <el-select v-model="form1.type1" clearable placeholder="请选择产品类型" @change="queryByName">
          <el-option v-for="(item, i) in type1" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型分类" prop="type2">
        <el-select v-model="form1.type2" placeholder="请选择类型分类">
          <el-option v-for="item in type2" :key="item.id" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="jiage">
        <el-input v-model="form1.jiage" placeholder="请输入价格"></el-input>
      </el-form-item>
      <el-form-item label="产品标题" prop="title">
        <el-input type="textarea" v-model="form1.title" placeholder="请输入产品标题"></el-input>
      </el-form-item>
      <el-form-item label="规格" prop="guige">
        <el-input v-model="form1.guige" placeholder="请输入规格"></el-input>
      </el-form-item>
      <el-form-item label="主料" prop="zhuliao">
        <el-input v-model="form1.zhuliao" placeholder="请输入主料"></el-input>
      </el-form-item>
      <el-form-item label="口感" prop="kougan">
        <el-input v-model="form1.kougan" placeholder="请输入口感"></el-input>
      </el-form-item>
      <el-form-item label="适应人群" prop="shiyingrenqun">
        <el-input v-model="form1.shiyingrenqun" placeholder="请输入适应人群"></el-input>
      </el-form-item>
      <el-form-item label="存储条件" prop="chucuntiaojian">
        <el-input v-model="form1.chucuntiaojian" placeholder="请输入存储条件"></el-input>
      </el-form-item>
      <el-form-item label="展示图片" prop="img">
        <el-upload class="avatar-uploader" action :show-file-list="false" :before-upload="beforeAvatarUpload"
          list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
          <img v-if="form1.img" style="object-fit:cover" :src="form1.img" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">修改商品</el-button>
        <el-button @click="$router.push('/home/commodity-list')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import httpApi from '@/myaxios';
import ObsClient from "esdk-obs-browserjs/src/obs";

export default {
  data() {
    return {
      imageUrl: "",
      initiateData: {
        option: {},
        uploadId: "",
      },
      fileUrl: "",

      dialogImageUrl: '',
      dialogVisible: false,
      type1: [],
      type2: [],
      type1name: -1,
      num: 0,
      rules: {
        name: [
          { required: true, message: '请输入品名', trigger: 'blur' }
        ],
        type1: [
          { required: true, message: '请选择产品类型', trigger: 'change' }
        ],
        type2: [
          { required: true, message: '请选择类型分类', trigger: 'change' }
        ],
        jiage: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入产品标题', trigger: 'blur' }
        ],
        guige: [
          { required: true, message: '请输入规格', trigger: 'blur' }
        ],
        zhuliao: [
          { required: true, message: '请输入主料', trigger: 'blur' }
        ],
        kougan: [
          { required: true, message: '请输入口感', trigger: 'blur' }
        ],
        shiyingrenqun: [
          { required: true, message: '请输入适应人群', trigger: 'blur' }
        ],
        chucuntiaojian: [
          { required: true, message: '请输入存储条件', trigger: 'blur' }
        ],
      },
      form1: {
        id: this.$route.params.id,
        name: "",
        type1: "",
        type2: "",
        jiage: '',
        title: "",
        guige: "",
        zhuliao: "",
        kougan: "",
        shiyingrenqun: "",
        chucuntiaojian: "",
        img: ""
      },
      rules: {
        jiage: [{ required: true, message: "请输入价格", trigger: "blur" },
        {
          pattern:
            /^[0-9]+\.{0,1}[0-9]{0,2}$/,
          message: "请输入正确的价格",
          trigger: "blur",
        },]
      }
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    queryByName(params) {
      console.log(params);
      this.type2 = []
      httpApi.commodity.queryByTypeName({ name: this.form1.type1 }).then(res => {
        for (let i = 0; i <= res.data[0].type.length; i++) {
          this.type2.push(res.data[0].type[i].name)
        }
      })
    },
    update() {
      console.log(this.form1);
      this.$refs['form'].validate(valid => {
        if (valid) {
          httpApi.commodity.updateById(this.form1).then(res => {
            if (res.status == 200) {
              this.$router.push('/home/commodity-list')
              this.$message.success('恭喜,修改成功！')
            }
          })
        }
      })

    },
    //通过id查询产品详情
    init() {
      let id = this.$route.params.id
      httpApi.commodity.queryById({ id }).then(res => {
        // console.log(res);
        this.form1 = res.data[0]
        // console.log(this.form1.type1);
      })
    },


    //图片上传
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      // return isJPG && isLt2M;
      if (isJPG && isLt2M) {
        var obsClient = new ObsClient({
          access_key_id: "CEQDVNAZTLD4SDTQFCTA", // 你的ak
          secret_access_key: "hr4oEqbvC7R0nW6BgqQKI6fA9a6FznVr4W7nGqLM", // 你的sk
          server: "https://obs.cn-north-4.myhuaweicloud.com", // 你的endPoint  记得加入https://
        });
        obsClient.putObject({
          Bucket: "daoxiangcun", // 桶名
          Key: file.name, // 文件名
          SourceFile: file, //流文件
        });
        this.form1.img = `https://daoxiangcun.obs.cn-north-4.myhuaweicloud.com/${file.name}`;
      }
    },
  },
  mounted() {
    this.init()
    httpApi.commodity.queryAll().then(res => {
      console.log("查询所有产品类型", res.data);
      for (let i = 0; i <= res.data.length; i++) {
        this.type1.push(res.data[i].name)
      }
    })
  },
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 100% !important;
  height: 100% !important;

}

.avatar-uploader .el-upload {
  border: 1px solid #292727;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>